<template>
  <view v-show="!isLoading" class="container" :style="appThemeStyle">
    <!-- 固定顶部导航栏 - 滚动时显示 -->
    <view class="sticky-tabs" :class="{ 'sticky-tabs-visible': showStickyTabs }">
      <view class="tab-item" :class="{ active: activeTab === 'product' }" @click="scrollToSection('product')">
        <text>商品</text>
      </view>
      <view class="tab-item" :class="{ active: activeTab === 'detail' }" @click="scrollToSection('detail')">
        <text>详情</text>
      </view>
      <view class="tab-item" :class="{ active: activeTab === 'comment' }" @click="scrollToSection('comment')">
        <text>评论</text>
      </view>
    </view>

    <!-- 商品部分 -->
    <view id="product-section" ref="productSection">
      <!-- 商品图片轮播 -->
      <SlideImage v-if="!isLoading" :video="goods.video" :videoCover="goods.videoCover" :images="goods.goods_images" />

      <!-- 商品信息 -->
      <view v-if="!isLoading" class="goods-info">
        <!-- 价格、销量 -->
        <view class="info-item info-item__top dis-flex flex-x-between flex-y-end">
          <view class="block-left dis-flex flex-y-center">
            <!-- 商品售价 -->
            <text class="floor-price__samll">￥</text>
            <text class="floor-price">{{ goods.goods_price_min }}</text>
            <!-- 会员价标签 -->
            <view v-if="goods.is_user_grade" class="user-grade">
              <text>会员价</text>
            </view>
            <!-- 划线价 -->
            <text v-if="goods.line_price_min > 0" class="original-price">￥{{ goods.line_price_min }}</text>
          </view>
          <view class="block-right dis-flex">
            <!-- 销量 -->
            <view class="goods-sales">
              <text>已售{{ goods.goods_sales }}件</text>
            </view>
          </view>
        </view>
        <!-- 标题、分享 -->
        <view class="info-item info-item__name dis-flex flex-y-center">
          <view class="goods-name flex-box">
            <text class="twoline-hide">{{ goods.goods_name }}</text>
          </view>
          <view class="goods-share__line"></view>
          <view class="goods-share">
            <button class="share-btn dis-flex flex-dir-column" @click="onShowShareSheet()">
              <text class="share__icon iconfont icon-fenxiang"></text>
              <text class="f-24">分享</text>
            </button>
          </view>
        </view>
        <!-- 商品卖点 -->
        <view v-if="goods.selling_point" class="info-item info-item_selling-point">
          <text>{{ goods.selling_point }}</text>
        </view>
      </view>

      <!-- 商品服务 -->
      <Service v-if="!isLoading" :goods-id="goodsId" />

      <!-- 选择商品规格 -->
      <view v-if="goods.spec_type == 20" class="goods-choice" @click="onShowSkuPopup(1)">
        <view class="spec-list">
          <view class="flex-box">
            <text class="col-8">选择：</text>
            <text class="spec-name" v-for="(item, index) in goods.specList" :key="index">{{ item.spec_name }}</text>
          </view>
          <view class="f-26 col-9 t-r">
            <text class="iconfont icon-arrow-right"></text>
          </view>
        </view>
      </view>
    </view>

    <!-- 详情部分 -->
    <view id="detail-section" ref="detailSection" class="detail-section">
      <!-- 规格参数表格 -->
      <view class="specs-table">
        <view class="specs-header">
          <text>规格参数</text>
        </view>
        
        <view class="specs-table-content">
          <!-- 商品编号 -->
          <view class="specs-row">
            <view class="specs-cell specs-label">
              <text>商品编号</text>
            </view>
            <view class="specs-cell specs-value">
              <text>{{ goods.goods_id || '暂无数据' }}</text>
            </view>
          </view>
          
          <!-- 企业名称 -->
          <view class="specs-row">
            <view class="specs-cell specs-label">
              <text>企业名称</text>
            </view>
            <view class="specs-cell specs-value">
              <text>{{ goods.company_name || '暂无数据' }}</text>
            </view>
          </view>
          
          <!-- 统一社会信用代码 -->
          <view class="specs-row">
            <view class="specs-cell specs-label">
              <text>统一社会信用代码</text>
            </view>
            <view class="specs-cell specs-value">
              <text>{{ goods.code || '暂无数据' }}</text>
            </view>
          </view>
          
          <!-- 其他规格参数行... -->
          <!-- 为了简洁，这里省略了其他规格参数行 -->
          
        </view>
      </view>

      <!-- 商品描述 -->
      <view v-if="!isLoading" class="goods-content">
        <view class="content-header">
          <text>商品描述</text>
        </view>
        <view v-if="goods.content != ''" class="goods-content__detail">
          <mp-html :content="goods.content" />
        </view>
      </view>
    </view>

    <!-- 评论部分 -->
    <view id="comment-section" ref="commentSection" class="comment-section">
      <view class="section-title">
        <text>买家评价</text>
      </view>
      
      <!-- 使用抽离出来的评价组件 -->
      <ReviewPopup :goods-id="goodsId">
        <Comment v-if="!isLoading" :goods-id="goodsId" :limit="2" />
      </ReviewPopup>
    </view>

    <!-- 商品SKU弹窗 -->
    <SkuPopup v-if="!isLoading" v-model="showSkuPopup" :skuMode="skuMode" :goods="goods" @addCart="onAddCart" />

    <!-- 底部选项卡 -->
    <view class="footer-fixed">
      <view class="footer-container">
        <!-- 导航图标 -->
        <view class="foo-item-fast">
          <!-- 首页 -->
          <view class="fast-item fast-item--home" @click="onTargetHome">
            <view class="fast-icon">
              <text class="iconfont icon-shouye"></text>
            </view>
            <view class="fast-text">
              <text>首页</text>
            </view>
          </view>
          <!-- 客服 -->
          <customer-btn v-if="isShowCustomerBtn" :showCard="true" :cardTitle="goods.goods_name" :cardImage="goods.goods_image"
            :cardPath="pagePath">
            <view class="fast-item">
              <view class="fast-icon">
                <text class="iconfont icon-kefu1"></text>
              </view>
              <view class="fast-text">
                <text>客服</text>
              </view>
            </view>
          </customer-btn>
          <!-- 购物车 -->
          <view class="fast-item fast-item--cart" @click="onTargetCart">
            <view v-if="cartTotal > 0" class="fast-badge fast-badge--fixed">{{ cartTotal > 99 ? '99+' : cartTotal }}
            </view>
            <view class="fast-icon">
              <text class="iconfont icon-gouwuche"></text>
            </view>
            <view class="fast-text">
              <text>购物车</text>
            </view>
          </view>
        </view>
        <!-- 操作按钮 -->
        <view class="foo-item-btn">
          <view class="btn-wrapper">
            <view v-if="isEnableCart" class="btn-item btn-item-deputy" @click="onShowSkuPopup(2)">
              <text>加入购物车</text>
            </view>
            <view class="btn-item btn-item-main" @click="onShowSkuPopup(3)">
              <text>立即购买</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 分享菜单 -->
    <share-sheet v-model="showShareSheet" :shareTitle="goods.goods_name" :shareImageUrl="goods.goods_image" />

  </view>
</template>

<script>
  import { getSceneData } from '@/core/app'
  import * as GoodsApi from '@/api/goods'
  import * as CartApi from '@/api/cart'
  import SettingModel from '@/common/model/Setting'
  import { GoodsTypeEnum } from '@/common/enum/goods'
  import ShareSheet from '@/components/share-sheet'
  import CustomerBtn from '@/components/customer-btn'
  import SlideImage from './components/SlideImage'
  import SkuPopup from './components/SkuPopup'
  import Comment from './components/Comment'
  import Service from './components/Service'
  import ReviewPopup from './components/ReviewPopup' // 导入新的评价组件

  export default {
    components: {
      ShareSheet,
      CustomerBtn,
      SlideImage,
      SkuPopup,
      Comment,
      Service,
      ReviewPopup // 注册评价组件
    },
    data() {
      return {
        // 正在加载
        isLoading: true,
        // 当前商品ID
        goodsId: null,
        // 商品详情
        goods: {},
        // 购物车总数量
        cartTotal: 0,
        // 显示/隐藏SKU弹窗
        showSkuPopup: false,
        // 模式 1:都显示 2:只显示购物车 3:只显示立即购买
        skuMode: 1,
        // 显示/隐藏分享菜单
        showShareSheet: false,
        // 是否支持加入购物车
        isEnableCart: false,
        // 是否显示在线客服按钮
        isShowCustomerBtn: false,
        // 展开的部分
        expandedSections: {
          registration: false,
          address: false,
          business: false,
          finance: false,
          tax: false,
          qualification: false
        },
        // 是否显示固定顶部导航
        showStickyTabs: false,
        // 当前激活的标签
        activeTab: 'product',
        // 各部分的位置信息
        sectionOffsets: {
          product: 0,
          detail: 0,
          comment: 0
        }
      }
    },
    computed: {
      // 当前页面链接
      pagePath() {
        const params = this.$getShareUrlParams({ goodsId: this.goodsId })
        return `/pages/goods/detail?${params}`
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
      // 记录query参数
      this.onRecordQuery(options)
      // 加载页面数据
      this.onRefreshPage()
      // 是否显示在线客服按钮
      this.isShowCustomerBtn = await SettingModel.isShowCustomerBtn()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      // 页面显示后，计算各部分的位置
      this.$nextTick(() => {
        setTimeout(() => {
          this.calculateSectionOffsets()
        }, 500)
      })
    },

    /**
     * 页面滚动时触发
     */
    onPageScroll(e) {
      // 滚动位置超过商品部分时显示顶部导航
      this.showStickyTabs = e.scrollTop > 300
      
      // 根据滚动位置更新当前激活的标签
      this.updateActiveTab(e.scrollTop)
    },

    methods: {
      // 记录query参数
      onRecordQuery(query) {
        const scene = getSceneData(query)
        this.goodsId = query.goodsId ? parseInt(query.goodsId) : parseInt(scene.gid)
      },

      // 刷新页面数据
      onRefreshPage() {
        const app = this
        app.isLoading = true
        Promise.all([app.getGoodsDetail(), app.getCartTotal()])
          .finally(() => {
            app.isLoading = false
            // 数据加载完成后，计算各部分的位置
            app.$nextTick(() => {
              setTimeout(() => {
                app.calculateSectionOffsets()
              }, 500)
            })
          })
      },

      // 获取商品信息
      getGoodsDetail() {
        const app = this
        return new Promise((resolve, reject) => {
          GoodsApi.detail(app.goodsId)
            .then(result => {
              app.goods = result.data.detail
              if (app.goods.goods_type == GoodsTypeEnum.PHYSICAL.value) {
                app.isEnableCart = true
              }
              resolve(result)
            })
            .catch(reject)
        })
      },

      // 获取购物车总数量
      getCartTotal() {
        const app = this
        return new Promise((resolve, reject) => {
          CartApi.total()
            .then(result => {
              app.cartTotal = result.data.cartTotal
              resolve(result)
            })
            .catch(reject)
        })
      },

      // 更新购物车数量
      onAddCart(total) {
        this.cartTotal = total
      },

      // 切换部分的展开/折叠状态
      toggleSection(section) {
        this.expandedSections[section] = !this.expandedSections[section]
        // 展开/折叠后，重新计算各部分的位置
        this.$nextTick(() => {
          setTimeout(() => {
            this.calculateSectionOffsets()
          }, 300)
        })
      },

      // 计算各部分的位置
      calculateSectionOffsets() {
        const query = uni.createSelectorQuery().in(this)
        
        query.select('#product-section').boundingClientRect(data => {
          if (data) {
            this.sectionOffsets.product = data.top
          }
        }).exec()
        
        query.select('#detail-section').boundingClientRect(data => {
          if (data) {
            this.sectionOffsets.detail = data.top
          }
        }).exec()
        
        query.select('#comment-section').boundingClientRect(data => {
          if (data) {
            this.sectionOffsets.comment = data.top
          }
        }).exec()
      },

      // 根据滚动位置更新当前激活的标签
      updateActiveTab(scrollTop) {
        // 获取当前页面滚动位置
        const currentScrollTop = scrollTop + 50 // 添加一点偏移量，使切换更自然
        
        // 根据滚动位置判断当前在哪个部分
        if (currentScrollTop >= this.sectionOffsets.comment) {
          this.activeTab = 'comment'
        } else if (currentScrollTop >= this.sectionOffsets.detail) {
          this.activeTab = 'detail'
        } else {
          this.activeTab = 'product'
        }
      },

      // 滚动到指定部分
      scrollToSection(section) {
        let selector = ''
        switch (section) {
          case 'product':
            selector = '#product-section'
            break
          case 'detail':
            selector = '#detail-section'
            break
          case 'comment':
            selector = '#comment-section'
            break
        }
        
        if (selector) {
          uni.createSelectorQuery().in(this).select(selector).boundingClientRect(data => {
            if (data) {
              // 获取页面滚动位置
              uni.pageScrollTo({
                scrollTop: data.top - 50, // 减去顶部导航的高度
                duration: 300
              })
            }
          }).exec()
        }
      },

      /**
       * 显示/隐藏SKU弹窗
       * @param {skuMode} 模式 1:都显示 2:只显示购物车 3:只显示立即购买
       */
      onShowSkuPopup(skuMode = 1) {
        const app = this
        if (app.isEnableCart) {
          app.skuMode = skuMode
        } else {
          app.skuMode = 3
        }
        app.showSkuPopup = !app.showSkuPopup
      },

      // 显示隐藏分享菜单
      onShowShareSheet() {
        this.showShareSheet = !this.showShareSheet
      },

      // 跳转到首页
      onTargetHome(e) {
        this.$navTo('pages/index/index')
      },

      // 跳转到购物车页
      onTargetCart() {
        this.$navTo('pages/cart/index')
      }
    },

    /**
     * 分享当前页面
     */
    onShareAppMessage() {
      return {
        title: this.goods.goods_name,
        path: this.pagePath
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      return {
        title: this.goods.goods_name,
        path: this.pagePath
      }
    }
  }
</script>

<style>
  page {
    background: #f7f7f7;
  }
</style>
<style lang="scss" scoped>
  @import "../detail.scss";

  /* 固定顶部导航 */
  .sticky-tabs {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 88rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;
    z-index: 999;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    transform: translateY(-100%);
    transition: transform 0.3s ease;
  }

  .sticky-tabs-visible {
    transform: translateY(0);
  }

  .tab-item {
    flex: 1;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #666;
    position: relative;
  }

  .tab-item.active {
    color: #ff4d4f;
    font-weight: 500;
  }

  .tab-item.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background-color: #ff4d4f;
    border-radius: 2rpx;
  }

  /* 商品信息样式 */
  .goods-info {
    background: #fff;
    padding: 20rpx 24rpx;
    margin-bottom: 20rpx;
  }

  /* 部分标题 */
  .section-title {
    padding: 24rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    background-color: #fff;
    margin-bottom: 2rpx;
  }

  /* 详情部分 */
  .detail-section {
    margin-bottom: 20rpx;
  }

  /* 评论部分 */
  .comment-section {
    margin-bottom: 120rpx; /* 为底部导航留出空间 */
  }

  /* 规格参数表格 */
  .specs-table {
    background-color: #fff;
    margin-bottom: 20rpx;
    overflow: hidden;
  }

  .specs-header {
    padding: 24rpx;
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    border-bottom: 1px solid #f5f5f5;
  }

  .specs-table-content {
    padding: 0;
    padding: 0 25px;
  }

  .specs-row {
    display: flex;
    border-bottom: 1px solid #ccc;
    border-right: 1px solid #ccc;
    border-left: 1px solid #ccc;
  }
  
  .specs-row:first-child {
    border-top: 1px solid #ccc;
  }

  .specs-cell {
    padding: 24rpx;
  }

  .specs-label {
    width: 220rpx;
    flex-shrink: 0;
    background-color: #fafafa;
    font-size: 26rpx;
    color: #666;
    border-right: 1px solid #ccc;
  }

  .specs-value {
    flex: 1;
    font-size: 26rpx;
    color: #333;
    word-break: break-all;
  }

  .multi-line {
    white-space: pre-wrap;
    line-height: 1.5;
  }

  .status-tag {
    display: inline-block;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    font-size: 24rpx;
  }

  .status-normal {
    background-color: #f6ffed;
    color: #52c41a;
    border: 1px solid #b7eb8f;
  }

  .status-abnormal {
    background-color: #fff2f0;
    color: #ff4d4f;
    border: 1px solid #ffccc7;
  }

  /* 商品描述 */
  .goods-content {
    background-color: #fff;
    margin-bottom: 20rpx;
  }

  .content-header {
    padding: 24rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    border-bottom: 1px solid #f5f5f5;
  }

  .goods-content__detail {
    padding: 24rpx;
  }

  /* 商品选择 */
  .goods-choice {
    background-color: #fff;
    padding: 24rpx;
    margin-bottom: 20rpx;
  }

  .spec-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .spec-name {
    margin-right: 16rpx;
    color: #333;
  }

  /* 底部按钮 */
  .footer-fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100;
  }

  .footer-container {
    display: flex;
    height: 100%;
  }

  .foo-item-fast {
    display: flex;
    width: 40%;
  }

  .fast-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
  }

  .fast-icon {
    height: 40rpx;
    line-height: 40rpx;
  }

  .fast-text {
    font-size: 22rpx;
    color: #666;
  }

  .fast-badge {
    position: absolute;
    top: 0;
    right: 10rpx;
    background-color: #ff4d4f;
    color: #fff;
    font-size: 20rpx;
    padding: 0 8rpx;
    border-radius: 20rpx;
    min-width: 32rpx;
    height: 32rpx;
    line-height: 32rpx;
    text-align: center;
  }

  .foo-item-btn {
    flex: 1;
    display: flex;
    align-items: center;
    padding-right: 20rpx;
  }

  .btn-wrapper {
    display: flex;
    width: 100%;
    height: 80rpx;
  }

  .btn-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: 28rpx;
    color: #fff;
    border-radius: 40rpx;
  }

  .btn-item-deputy {
    background-color: #ff9500;
    margin-right: 20rpx;
  }

  .btn-item-main {
    background-color: #ff4d4f;
  }
</style>